package com.avic.rong.userOrder.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.userOrder.api.InvoiceDetailByTargetIdApi;
import com.avic.rong.userOrder.bean.FaPiaoDetailsBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.OkHttpUtils;
import com.avic.rong.utils.SDCardUtils;
import com.avic.rong.utils.TimeUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;

import java.io.File;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;


import butterknife.BindView;
import butterknife.ButterKnife;

public class FaPiaoDetailsActivity extends BaseActivity {


    @BindView(R.id.tv_order_sn)
    TextView tvOrderSn;
    @BindView(R.id.tv_below_order_time)
    TextView tvBelowOrderTime;
    @BindView(R.id.tv_fapiao_type)
    TextView tvFapiaoType;
    @BindView(R.id.look_fapiao_btn)
    TextView lookFapiaoBtn;
    @BindView(R.id.tv_fapiao_content)
    TextView tvFapiaoContent;
    @BindView(R.id.tv_fapiao_taitou)
    TextView tvFapiaoTaitou;
    @BindView(R.id.tv_fapiao_state)
    TextView tvFapiaoState;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;

    @BindView(R.id.tv_fapiao_identify)
    TextView tv_fapiao_identify;
    @BindView(R.id.ll_identify)
    LinearLayout ll_fapiao_identify;

    @BindView(R.id.download_fapiao_btn)
    TextView download_fapiao_btn;
    @BindView(R.id.tv_tip)
    TextView tv_tip;

    private String order_id;
    private String order_sn;
    private String order_type;

    private String ejsPdfUrl;
    private  String savePath;
    @Override
    protected int getContentViewId() {
        return R.layout.activity_fa_piao_details;
    }

    @Override
    protected void initView() {
        tvTitle.setText("发票详情");
        tv_tip.setAlpha(0.4f);
        ivRight.setImageResource(R.mipmap.gouwuche_dot);
        if (TextUtils.isEmpty(getIntent().getStringExtra("order_id")) && TextUtils.isEmpty(getIntent().getStringExtra("order_sn"))) {
            return;
        }
        order_id = getIntent().getStringExtra("order_id");
        order_sn = getIntent().getStringExtra("order_sn");
        order_type = getIntent().getStringExtra("order_type");

        //发票详情
        faPiaoDetails();

    }

    @Override
    protected void addListener() {
        //查看发票图片
        lookFapiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(ejsPdfUrl + "")) return;
                goLookFaPiaoActivity(ejsPdfUrl + "");
            }
        });

        download_fapiao_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DialogCustom.showDoubleDialog(FaPiaoDetailsActivity.this, "提示", "是否下载发票？", "否", "是", new DialogCustom.CustomDialogDouble() {
                    @Override
                    public void rightButtonClicked() {
                    downloadFaPiao();
                    }

                    @Override
                    public void leftButtonClicked() {

                    }
                });

            }
        });
    }

    private void downloadFaPiao() {
        savePath = SDCardUtils.getSDCardPath() + "rong" + File.separator;
        //去寻找是否已经有了读写的权限
        if (ContextCompat.checkSelfPermission(FaPiaoDetailsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){

            //Toast.makeText(MainActivity.this,"您申请了动态权限",Toast.LENGTH_SHORT).show();
            if (ejsPdfUrl==null){
                ToastTools.showToast("请获取下载地址");
                return;
            }
            downloadFile(ejsPdfUrl,savePath);

        }else{
            //否则去请求读写权限
            ActivityCompat.requestPermissions(FaPiaoDetailsActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);

        }
    }

    private void faPiaoDetails() {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> paramsBody = new HashMap<>();
            paramsBody.put("token", getSharedPreferencesUtil().getLogintoken());
            if (!TextUtils.isEmpty(order_id)) {
                paramsBody.put("targetId", order_id);
            } else {
                paramsBody.put("targetId", order_sn);
            }

//            发票来源：1：订单发票 (软件服务/元器件)2：充值发票 3：培训订单发票4：标准订单发票
            if (!order_type.equals("5")) {
                paramsBody.put("invFrom", "1");
            } else {
                paramsBody.put("invFrom", "3");
            }

            final InvoiceDetailByTargetIdApi invoiceDetailByTargetIdApi = new InvoiceDetailByTargetIdApi(this, simpleOnNextListener);
            invoiceDetailByTargetIdApi.setCache(false);
            invoiceDetailByTargetIdApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(invoiceDetailByTargetIdApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(invoiceDetailByTargetIdApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    //权威评测
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
//            listData.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(FaPiaoDetailsActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            FaPiaoDetailsBean faPiaoDetailsBean = (FaPiaoDetailsBean) subjects.getData();
            if (faPiaoDetailsBean != null) {


                tvOrderSn.setText(faPiaoDetailsBean.getTarget() + "");
                if (faPiaoDetailsBean.getInvType() == 2) {
                    tvFapiaoType.setText("增值税专用发票");
                } else if (faPiaoDetailsBean.getInvType() == 3) {
                    tvFapiaoType.setText("电子普通发票");
                }
                tvFapiaoContent.setText(faPiaoDetailsBean.getInvContent());
                if (faPiaoDetailsBean.getInvPayeeType() == 1) {
                    tvFapiaoTaitou.setText("个人");
                } else if (faPiaoDetailsBean.getInvPayeeType() == 2) {
                    tvFapiaoTaitou.setText(faPiaoDetailsBean.getInvPayee());
                }
                if (faPiaoDetailsBean.getStatus() == 0) {
                    //未付款
                    tvFapiaoState.setText("未付款");
                } else if (faPiaoDetailsBean.getStatus() == 1) {
                    //已开发票
                    tvFapiaoState.setText("已开发票");
                    if (!TextUtils.isEmpty(faPiaoDetailsBean.getEjsPdfUrl())&&!faPiaoDetailsBean.getEjsPdfUrl().equals("null")) {
                        lookFapiaoBtn.setVisibility(View.VISIBLE);
                        download_fapiao_btn.setVisibility(View.VISIBLE);
                        ejsPdfUrl = faPiaoDetailsBean.getEjsPdfUrl();
                    }else {
                        lookFapiaoBtn.setVisibility(View.GONE);
                        download_fapiao_btn.setVisibility(View.GONE);
                    }


                } else if (faPiaoDetailsBean.getStatus() == 3 || faPiaoDetailsBean.getStatus() == 4 || faPiaoDetailsBean.getStatus() == 5 || faPiaoDetailsBean.getStatus() == 6 || faPiaoDetailsBean.getStatus() == 7) {
                    //开票中
                    tvFapiaoState.setText("开票中");
                } else if (faPiaoDetailsBean.getStatus() == 9 || faPiaoDetailsBean.getStatus() == 10 || faPiaoDetailsBean.getStatus() == 11 || faPiaoDetailsBean.getStatus() == 13) {
                    //发票红冲中
                    tvFapiaoState.setText("发票红冲中");
                } else if (faPiaoDetailsBean.getStatus() == 12) {
                    //发票已红冲
                    tvFapiaoState.setText("发票已红冲");
                } else if (faPiaoDetailsBean.getStatus() == 8) {
                    //无需开票
                    tvFapiaoState.setText("无需开票");
                }


                if (!TextUtils.isEmpty(faPiaoDetailsBean.getInvPayeeNumber())) {
                    tv_fapiao_identify.setText(faPiaoDetailsBean.getInvPayeeNumber() + "");
                    ll_fapiao_identify.setVisibility(View.VISIBLE);
                } else {
                    ll_fapiao_identify.setVisibility(View.GONE);
                }


                tvBelowOrderTime.setText(TimeUtil.strToDate(faPiaoDetailsBean.getOrderAddTime()+""));
            }


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    private void goLookFaPiaoActivity(String faPiaoUrl) {
        Intent intent = new Intent(FaPiaoDetailsActivity.this, LookFaPiaoActivity.class);
        intent.putExtra("faPiaoUrl", faPiaoUrl);
        startActivity(intent);
    }
    //0 失败   1成功   2  进度
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0){
//                tv_tip.setVisibility(View.VISIBLE);
                ToastTools.showToast(FaPiaoDetailsActivity.this,"下载失败");
            }else if (msg.what==1){
//                tv_tip.setVisibility(View.GONE);
                ToastTools.showToast(FaPiaoDetailsActivity.this,"下载成功");
            }else if (msg.what==2){
//                tv_tip.setVisibility(View.VISIBLE);
//                tv_tip.setText("正在加载("+progress+"/100)");
////                tvPage.setText("正在加载("+progress+"/100)");
            }
        }
    };
    private void downloadFile(String path,String savePath){
        OkHttpUtils.build().download(path, savePath, new OkHttpUtils.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {

                handler.sendEmptyMessage(1);
            }
            @Override
            public void onDownloading(int progress) {
//                tv_tip.setVisibility(View.VISIBLE);
//                tv_tip.setText("正在加载("+progress+"/100)");
////                tvPage.setText("正在加载("+progress+"/100)");
//                handler.sendEmptyMessage(2);
            }
            @Override
            public void onDownloadFailed() {
//                Log.i("JAVA", "onDownloadFailed");
////                tvPage.setText("加载失败..");
//                tv_tip.setVisibility(View.VISIBLE);
//                tv_tip.setText("加载失败...");
                handler.sendEmptyMessage(0);
            }
        });
    }

}
